﻿using Chaotic.Core.Extension;
using Chaotic.DataBase.DBAccessLibrary.Model;
using Chaotic.Module.DBTool.Common;
using Chaotic.Module.DBTool.Models;
using Chaotic.Module.DBTool.ViewModels;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using Telerik.Windows.Controls;

namespace Chaotic.Module.DBTool.Views
{
    /// <summary>
    /// DBMasterContent.xaml 的交互逻辑
    /// </summary>
    public partial class DBMasterContent : UserControl
    {
        private readonly IDBRabbionCommandMenu _dBRabbionCommandMenu;
        public DBMasterContent(IEventAggregator eventAggregator, IDBRabbionCommandMenu dBRabbionCommandMenu)
        {
            InitializeComponent();
            _dBRabbionCommandMenu = dBRabbionCommandMenu;
            Application.Current.MainWindow.Closing += MainWindow_Closed;
            dBRabbionCommandMenu.GetActionDocumentControl = () => _actionDocumentContent;
 
            eventAggregator.ResgiterMessage<DBToolMessage>(message =>
            {
                if (message.Target == nameof(DBMasterContent))
                {
                    switch(message.ActionName)
                    {
                        case "AddSqlDocument":
                            {
                                if (message.Data is SqlDocumentData sqlDocumentData)
                                {
                                    try
                                    {
                                        AddSqlDocument(sqlDocumentData.FilePath,
                                            sqlDocumentData.IsNewFile, sqlDocumentData.SqlContent);
                                    }
                                    catch (Exception ex)
                                    {
                                        eventAggregator.SendLogMessage(ex.Message, true);
                                    }
                                }
                            }
                            break;
                        case "AddTableDefinitionDocument":
                            {
                                if (message.Data is TableEntity table)
                                {
                                    try
                                    {
                                        AddTableDefinitionDocument(table);
                                    }
                                    catch (Exception ex)
                                    {
                                        eventAggregator.SendLogMessage(ex.Message, true);
                                    }
                                }
                            }
                            break;
                        case "AddOutPutPane":
                            {
                                if (message.Data is string sqlContent)
                                {
                                    try
                                    { 
                                        //拆分sql  按照；分割
                                        SqlParserManager.Instance.SplitSqlStatements(sqlContent,out List<string> searchSql,out List<string> execSql);
                                        
                                        //删除多余的输出面板
                                        RemoveExtraOutPutPane();

                                        OutPutGridContentViewModel? outPutContentViewModel = outPutContent.DataContext as OutPutGridContentViewModel;

                                        outPutContentViewModel?.ExecSqlAsync(execSql); 

                                        for (int i=0;i< searchSql.Count; i++)
                                        {
                                            if (i == 0)
                                            {
                                                outPutContentViewModel?.LoadDataAsync(searchSql[i]);
                                            }
                                            else
                                            {
                                                AddOutPutPane($"输出{i + 1}", searchSql[i]);
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        eventAggregator.SendLogMessage(ex.Message, true);
                                    }
                                }
                            }
                            break;
                    }
                    
                }
            }); 
        }

        private void MainWindow_Closed(object? sender, EventArgs e)
        {
            bool isSave = false;
            //保存当前打开的文档
            List<SqlOpenDocument> openDocumentList = new List<SqlOpenDocument>();
            foreach (var item in documentGroup.Items)
            {
                if (item is RadDocumentPane { DataContext: SqlContentViewModel sqlContentViewModel })
                {
                    if(sqlContentViewModel.IsChangeDocument)
                    {
                        if (!isSave)
                        {
                            if (MessageBoxExtension.ShowConfirm("是否要保存修改的文件？", "保存", "保存"))
                            {
                                isSave = true;
                            }
                        }

                        if(isSave)
                            sqlContentViewModel.Save();
                    }
                    if (!sqlContentViewModel.IsNewDocument)
                    {
                        openDocumentList.Add(new SqlOpenDocument
                        {
                            FilePath = sqlContentViewModel.FilePath
                        }); 
                    }
                }
            }

            if (openDocumentList.Count > 0)
            {
                string directoryPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Document");
                if (!Directory.Exists(directoryPath))
                    Directory.CreateDirectory(directoryPath);
                string filePath = Path.Combine(directoryPath, "OpenDocument.dat");
                JsonDataBaseConverter jsonDataBaseConverter = new JsonDataBaseConverter();
                openDocumentList.SerializeDataToFile(filePath, jsonDataBaseConverter);
            }
        }

        object _actionDocumentContent;
        private void raddock_ActivePaneChanged(object sender, Telerik.Windows.Controls.Docking.ActivePangeChangedEventArgs e)
        {
            if (e.NewPane == null)
                return;

            if (e.NewPane is RadDocumentPane)
            {
                _actionDocumentContent = e.NewPane.Content;
                _dBRabbionCommandMenu.RaiseCanExecuteChangedByActive();
            }
        }

        //新增SQL编辑文档
        private void AddSqlDocument(string filepath,bool isNew, SqlContentMessage? msg)
        {
            var sqlContent = new SqlContent();  
            string title = isNew ? "新文档" : Path.GetFileName(filepath);

            if (sqlContent.DataContext is SqlContentViewModel sqlContentViewModel)
            {
                sqlContentViewModel.DocumentHeaderTitle = title;
                sqlContentViewModel.FilePath = filepath;
                sqlContentViewModel.IsNewDocument = isNew;

                var pane = new RadDocumentPane
                {
                    Content = sqlContent,
                    DataContext = sqlContentViewModel,
                    HeaderTemplate = this.Resources["documentHeaderTemplate"] as DataTemplate,
                };

                documentGroup.Items.Add(pane);
                raddock.ActivePane = pane;

                if (msg != null)
                    sqlContentViewModel.InsertSql(msg);
            }
        }

        //新增表结构文档
        private void AddTableDefinitionDocument(TableEntity table)
        {
            var tableDefinitionContent = new TableDefinitionContent();
            if (tableDefinitionContent.DataContext is TableDefinitionContentViewModel tableDefinitionContentViewModel)
            {
                tableDefinitionContentViewModel.Init(table);

                var pane = new RadDocumentPane
                {
                    Content = tableDefinitionContent,
                    DataContext = tableDefinitionContentViewModel,
                    HeaderTemplate = this.Resources["documentHeaderTemplate"] as DataTemplate,
                };
                documentGroup.Items.Add(pane);
                raddock.ActivePane = pane;
            }
        }

        //新增输出面板
        private void AddOutPutPane(string title,string sql)
        {
            OutPutGridContent outPutGridContent = new OutPutGridContent(sql);

            RadPane radPane = new RadPane
            {
                Header = title,
                Content = outPutGridContent
            }; 
            bottomRadPaneGroup.Items.Add(radPane);
        }

        //删除多余的输出面板
        private void RemoveExtraOutPutPane()
        {
            List<RadPane> removePanes = new List<RadPane>();
            foreach(var item in bottomRadPaneGroup.Items)
            {
                if(item is RadPane { Content: OutPutGridContent, CanUserClose: true } radPane)
                {
                    removePanes.Add(radPane);
                }
            }
            foreach(var removePane in removePanes)
            {
                bottomRadPaneGroup.Items.Remove(removePane);
            }
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            //读取上次打开的文件
            string directoryPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Document");
            if (!Directory.Exists(directoryPath))
                Directory.CreateDirectory(directoryPath);
            string filePath = Path.Combine(directoryPath, "OpenDocument.dat");
            if (File.Exists(filePath))
            {
                var jsonDataBaseConverter = new JsonDataBaseConverter();
                List<SqlOpenDocument> openDocuments = DataCompression.DeserializeDataToFile<List<SqlOpenDocument>>(filePath, jsonDataBaseConverter);
                foreach (var openDocument in openDocuments)
                {
                    AddSqlDocument(openDocument.FilePath, false,null);
                }
            }
            else
            {
                //默认打开一个空文档
                AddSqlDocument(string.Empty, true, null);
            }
        }
 
        private void raddock_PreviewClose(object sender, Telerik.Windows.Controls.Docking.StateChangeEventArgs e)
        {
            if(e.Panes.Any())
            {
                if(e.Panes.FirstOrDefault()?.DataContext is SqlContentViewModel { IsChangeDocument: true } sqlContentViewModel)
                {
                    if (MessageBoxExtension.ShowConfirm($"是否要保存对 {sqlContentViewModel.DocumentHeaderTitle} 的更改？", "保存", "保存"))
                    {
                        sqlContentViewModel.Save();
                    }
                }
            } 
        }
 
    }
}
